package com.glwan.fixedassetapp.components;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.glwan.fixedassetapp.R;

public class SelectView extends LinearLayout {

    private ListView listView;

    private EditText selectText;

    private EditText selectSearchText;

    private TextView selectSuffix;

    private PopupWindow popupWindow;

    private int selectPosition = 0;

    private LinearLayout selectHeaderLinearLayout;

    public SelectView(Context context) {
        this(context, null);
    }

    public SelectView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public SelectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public SelectView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context, attrs, defStyleAttr, defStyleRes);
    }

    private void initView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SelectView, defStyleAttr, defStyleRes);
        int expandHeight = attributes.getInteger(R.styleable.SelectView_expandHeight, 300);
        String selectTextHint = attributes.getString(R.styleable.SelectView_selectTextHint);

//        setOrientation(LinearLayout.VERTICAL);

        // 设置主视图的布局参数
        LayoutParams layoutParams = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        setLayoutParams(layoutParams);


        //构建选择头部的视图
        LinearLayout selectHeaderLinearLayout = new LinearLayout(getContext());
        selectHeaderLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
        selectHeaderLinearLayout.setLayoutParams(new LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        selectHeaderLinearLayout.setGravity(Gravity.CENTER);
        selectHeaderLinearLayout.setPadding(10, 0, 10, 0);


        selectSearchText = new EditText(getContext());
        selectSearchText.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        selectSearchText.setBackground(null);
        selectSearchText.setHint("请输入");
        selectSearchText.setVisibility(GONE);
        selectHeaderLinearLayout.addView(selectSearchText);

        selectText = new EditText(getContext());
        selectText.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        selectText.setFocusableInTouchMode(false);
        selectText.setBackground(null);

//        Log.i("selectTextHint", selectTextHint);
        if (selectTextHint != null) {
            selectText.setHint(selectTextHint);
        } else {
            selectText.setHint("Touch to select");
        }
        selectHeaderLinearLayout.addView(selectText);

        selectSuffix = new TextView(getContext());
        LayoutParams selectSuffixLayoutParams = new LayoutParams(20, 20);
        selectSuffix.setLayoutParams(selectSuffixLayoutParams);
        selectSuffix.setBackground(getContext().getDrawable(R.drawable.down));
        selectSuffix.setTextColor(Color.parseColor("#333333"));


        LinearLayout selectSuffixLinearLayout = new LinearLayout(getContext());
        selectSuffixLinearLayout.setLayoutParams(new LinearLayoutCompat.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        selectSuffixLinearLayout.setPadding(10, 10, 10, 10);
        selectHeaderLinearLayout.setGravity(Gravity.CENTER);
        selectSuffixLinearLayout.addView(selectSuffix);

        selectHeaderLinearLayout.addView(selectSuffixLinearLayout);

        addView(selectHeaderLinearLayout);

        //构建下拉列表
        listView = new ListView(getContext());

//        List<String> itemList = new ArrayList<>();
//        itemList.add("Item 1");
//        itemList.add("Item 2");
//        itemList.add("Item 3");
//        itemList.add("Item 4");
//        itemList.add("Item 5");
//        listView.setAdapter(new ArrayAdapter<>(
//                getContext(),
//                R.layout.support_simple_spinner_dropdown_item,
//                itemList
//        ));

        listView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, expandHeight));


        LinearLayout listViewLinearLayout = new LinearLayout(getContext());
        listViewLinearLayout.setLayoutParams(new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        listViewLinearLayout.setOrientation(LinearLayout.VERTICAL);
        listViewLinearLayout.addView(listView);
        //需要给定固定高度
        popupWindow = new PopupWindow(listViewLinearLayout, LayoutParams.WRAP_CONTENT, expandHeight, false);

        popupWindow.setBackgroundDrawable(getPopupWindowBackground());
        popupWindow.setOutsideTouchable(false);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        selectText.setOnClickListener(view -> {
            viewToggle();
        });

        //设置监听事件
        selectSuffixLinearLayout.setOnClickListener(view -> {
            viewToggle();
        });

        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            Adapter adapter = adapterView.getAdapter();
            selectText.setText(String.valueOf(adapter.getItem(i)));
            selectPosition = i;
            hide();
        });

        selectSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.i("selectSearchText", charSequence.toString());
                Filterable filterable = (Filterable) listView.getAdapter();
                if (filterable != null) {
                    filterable.getFilter().filter(charSequence);
//                    popupWindow.update();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void viewToggle() {
        if (popupWindow.isShowing()) {
            hide();
        } else {
            show();
        }
    }

    private Drawable getPopupWindowBackground() {
        int strokeWidth = 1; // 边框宽度
        int strokeColor = Color.GRAY; // 边框颜色
        int fillColor = Color.WHITE; // 背景颜色

        GradientDrawable drawable = new GradientDrawable();
        drawable.setStroke(strokeWidth, strokeColor);
        drawable.setColor(fillColor);

        return drawable;
    }

    private void show() {
        setBackground(getPopupWindowBackground());
        selectSearchText.setText("");
        selectText.setVisibility(GONE);
        selectSearchText.setVisibility(VISIBLE);

        popupWindow.showAsDropDown(selectSearchText);

        selectSuffix.setBackground(getContext().getDrawable(R.drawable.up));
        // 将焦点设置到selectSearchText
    }

    private void hide() {
        setBackground(null);
        selectText.setVisibility(VISIBLE);
        selectSearchText.setVisibility(GONE);
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(selectSearchText.getWindowToken(), 0);
        selectSuffix.setBackground(getContext().getDrawable(R.drawable.down));
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }


    public void setAdapter(ListAdapter adapter) {
        listView.setAdapter(adapter);
    }

    public String getSelectTextValue() {
        return selectText.getText().toString();
    }

    public void setSelectedItem(int i) {
        ListAdapter adapter = listView.getAdapter();
        if (adapter != null) {
            if (i < adapter.getCount()) {
                selectText.setText(String.valueOf(adapter.getItem(i)));
            }
        }
    }

    public int getSelectedItemPosition() {
        return selectPosition;

    }
}
